package com.atguigu.imperial.court.dao;

import com.atguigu.imperial.court.util.JDBCUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class BaseDao<T> {
    private QueryRunner runner=new QueryRunner();
    public T getSingleBean(String sql,Class<T> entityClass,Object ... parameters){
        try {
            Connection connection = JDBCUtils.getConnection();

            T entity=runner.query(connection,sql,new BeanHandler<>(entityClass),parameters);
            return entity;
        } catch (SQLException e) {
            e.printStackTrace();
            new RuntimeException(e);
        }
        return null;
    }
    public int update(String sql,Object ... parameters){
        Connection connection = JDBCUtils.getConnection();
        try {
            int affecteRowNumbers=runner.update(connection,sql,parameters);
            return affecteRowNumbers;
        } catch (SQLException e) {
            e.printStackTrace();
            new RuntimeException(e);
            return 0;
        }
    }
    public List<T> getBeanList(String sql,Class<T> entityClass,Object...parameters){
        Connection connection = JDBCUtils.getConnection();
        try {
            return runner.query(connection,sql,new BeanListHandler<>(entityClass),parameters);
        } catch (SQLException e) {
            e.printStackTrace();
            new RuntimeException(e);
        }
        return  null;
    }
}
